package com.weiaibenpao.demo.chislim.base;

import android.content.Context;
import android.view.View;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by wlx on 2017/12/4.
 */

public abstract class BasePresenter<V extends BaseView> {
        protected Context mContext;

        protected CompositeDisposable mCompositeDisposable=new CompositeDisposable();

    /**
     *View的弱引用
     */

    protected WeakReference<V> mWeakReference;

    /**
     * 在 Activity／Fragment 销毁生命周期中取消异步操作防止内存泄露：
     */
    public void  onDestroy(){
        cancelNetWork();
    }

    /**
     *  解除订阅的方式
     *
     */
    private void cancelNetWork() {
        if (mCompositeDisposable!=null){
            mCompositeDisposable.dispose();
//            mCompositeDisposable.clear();
        }
    }

    /**
     * 注入view
     * @param mView
     */
   public void  attack(V mView){
       mWeakReference=new WeakReference<V>(mView);
       getContext();
   }

    /**
     * 销户view
     */
   public void detach(){
       if (null!=mWeakReference){
           mWeakReference.clear();
       }
   }
   protected V getView(){
       return mWeakReference.get();
   }

    /**
     * 获取context
     */
    public void getContext() {
        if (getView() instanceof BaseActivity){
         mContext= (Context) getView();
        }else if (getView() instanceof BaseFragment){
            mContext= ((BaseFragment) getView()).getActivity();
        }else if (getView() instanceof View){
            mContext=((View) getView()).getContext();
        }else {
           throw new IllegalArgumentException("view must instanceof activity or fragment");
        }
    }
}
